package com.xmall.auth.security.provider;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xmall.auth.define.dict.AccountTypeEnum;
import com.xmall.auth.entity.MemberAccount;
import com.xmall.auth.service.IMemberAccountService;
import com.xmall.auth.service.remote.MemberServiceFeign;
import com.xmall.auth.utils.PasswordUtils;
import com.xmall.define.base.Result;
import com.xmall.define.base.ResultCode;
import com.xmall.exception.XmallException;
import com.xmall.define.dto.login.MemberDto;
import com.xmall.define.dto.login.MemberLoginInfo;
import com.xmall.security.MemberPhonePasswordAuthenticationToken;
import org.springframework.beans.BeanUtils;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * 用户登录校验
 */
@Component
public class MemberPhonePasswordAuthenticationProvider implements AuthenticationProvider {

    @Resource
    private IMemberAccountService memberAccountService;

    @Resource
    private MemberServiceFeign memberServiceFeign;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        MemberPhonePasswordAuthenticationToken token = (MemberPhonePasswordAuthenticationToken)authentication;

        // 查询用户
        QueryWrapper<MemberAccount> query = new QueryWrapper<MemberAccount>()
                .eq("type", AccountTypeEnum.PHONE.getType())
                .eq("account", token.getPrincipal());
        MemberAccount memberAccount = memberAccountService.getOne(query);
        if(null == memberAccount){
            throw new XmallException(ResultCode.AUTH_LOGIN_ERROR);
        }

        // 验证密码
        if(!PasswordUtils.checkPassword((String) token.getCredentials(), memberAccount.getPassword())){
            throw new XmallException(ResultCode.AUTH_LOGIN_ERROR);
        }

        // 登录信息
        MemberLoginInfo loginInfo = new MemberLoginInfo();
        BeanUtils.copyProperties(memberAccount, loginInfo);

        // 用户信息
        Result<MemberDto> result = memberServiceFeign.memberInfo(loginInfo.getUserId());
        if(null == result || !result.callSuccess()){
            throw new XmallException(ResultCode.AUTH_LOGIN_ERROR);
        }
        BeanUtils.copyProperties(result.getData(), loginInfo);

        return new MemberPhonePasswordAuthenticationToken(loginInfo, loginInfo.getAccount(), Arrays.asList());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return MemberPhonePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
